import WebGLPlayer from "../WebGLPlayer.js";

export default class Player {
  myWs = null;
  worker = null;
  timer = null;

  constructor(address, canvas, stateChange) {
    const player = new WebGLPlayer(canvas);
    this.createWS(
      address,
      (data) => {
        // 调用解码器
        player.render(new Uint8Array(data), 1920, 1080);
      },
      "arraybuffer",
      stateChange.bind(this)
    );
  }

  // 重连计数
  connCount = 0;
  createWS = (url, cb, binaryType, stateChange) => {
    // websocket开启前提是解码器已经实例化
    if (this.connCount === 0) {
      stateChange(0, `正在连接${url}...`);
    }
    const ws = new WebSocket(url);
    if (binaryType) {
      ws.binaryType = binaryType;
    }
    ws.onopen = () => {
      stateChange(1, `已连接${url}`);
    };
    ws.onmessage = (e) => {
      cb(e.data);
    };
    // 需要服务端响应了才会触发，因此服务器端延时会造成客户端关闭延时
    ws.onclose = () => {
      console.log("监听到服务端断开");
      this.connCount += 1;
      stateChange(2, `正在重连${url},第${this.connCount}次...`);
      // 服务器断开连接需要自动重连
      this.timer = setTimeout(() => {
        this.createWS(url, cb, binaryType, stateChange);
      }, 1500);
    };
    this.myWs = ws;
  };

  dispose() {
    if (this.myWs) {
      this.myWs.close();
      this.myWs = null;
    }
  }
}
